package com.aaa.service.impl;

import com.aaa.dao.RoleDao;
import com.aaa.entity.Role;
import com.aaa.exception.SaveRoleMenuException;
import com.aaa.service.RoleService;
import com.aaa.util.DefaultMsg;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色管理service实现类
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {
    @Resource
    private RoleDao roleDao;
    @Override
    public DefaultMsg savePermits(Integer rid, String mids) {
        DefaultMsg defaultMsg=new DefaultMsg();
        //保存之前旧的权限信息删除
        Integer count = roleDao.deleteRoleMenuByRid(rid);

        //先把mids字符串([1,3,6,4])转换成List 有序列表
        List<Double> list = new Gson().fromJson(mids, List.class);
        //遍历list 一条一条往role_menu表存数据
        for (Double mid:list){
            //受影响的行数
            count = roleDao.saveRoleMenu(rid, mid.intValue());
            //判断如果count  不大于0
            if (count==0){
                /*defaultMsg.setSuccess(0);
                defaultMsg.setError("保存角色信息失败");*/

                //向外抛出一个运行时异常
                throw new SaveRoleMenuException("保存角色菜单信息失败");
            }
        }
        return defaultMsg;
    }

    @Override
    public List<Integer> listMidsByRid(Integer rid) {
        return roleDao.listMidsByRid(rid);
    }
}
